package services

import (
	"context"
	serverCommon "fiberCommonUtils/common"
	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

func (some *ServiceSold) ConditionServiceSoldForClient(clientID *primitive.ObjectID) bson.E {
	return bson.E{Key: "client_id", Value: *clientID}
}

func ClientReadHeBoughtServices(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	state := c.Query("state")
	_clientID := c.Locals("ClientID").(primitive.ObjectID)
	result := ServiceSoldList{}
	filter := bson.D{
		*mongoDB.CommonFilterNotDeleted(),
		(&ServiceSold{}).ConditionServiceSoldForClient(&_clientID),
		{Key: "canceled", Value: false},
	}
	if state == "waitBoard" {
		filter = append(filter, bson.E{Key: "used", Value: false})
	} else {
		filter = append(filter, bson.E{Key: "used", Value: true})
	}
	err := result.Find(ctx, &filter)
	if err != nil {
		return err
	}
	return c.JSON(serverCommon.MakeSuccessJson(result))
}

// ServiceSoldList 列表查询
type ServiceSoldList []ServiceSold

func (l *ServiceSoldList) Find(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	coll := (&ServiceSold{}).GetCollection()
	cursor, err := coll.Find(ctx, filter, opts...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, l)
}
